


import './forms.scss'
import { useFormItemInit } from './hooks';
import { FormItemBaseProps } from './interface';
import React from 'react';
import { CloseCircleOutlined, MenuOutlined } from '@ant-design/icons';
import { CascadePicker } from 'antd-mobile';
import Readonly from './Readonly';
import { Utils } from '../../utils/utils';
import { Components } from '../..';



interface Option {
    value: string | number;
    label?: React.ReactNode;
    children?: Option[];
}

interface IProps extends FormItemBaseProps {
}

export const formatCascaderValue = (spliceValue: string) => {
    if (Utils.isEmpty(spliceValue)) {
        return undefined;
    }
    if (Utils.isString(spliceValue)) {
        const arr = spliceValue.split(',');
        const numArr = arr.map(item => {
            return isNaN(Number(item)) ? item : Number(item);
        });
        return numArr;
    }
    return undefined;
}

const findOptionsLable = (key: any, options: Option[]): Option | undefined => {
    let result = options.find(v => v.value === key);
    if (result) {
        return result;
    }
    options.forEach(option => {
        const children = option.children ?? [];
        const res = findOptionsLable(key, children);
        if (res !== undefined) {
            result = res;
        }
    });
    return result;
}

export const findCascaderLabel = (value: any[] | undefined, options: Option[]): string[] => {
    let result: string[] = [];
    if (Array.isArray(value)) {
        value.forEach(item => {
            const option = findOptionsLable(item, options);
            if (option) {
                result.push(option.label as string);
            }
        });
    }
    return result;
}

/** id => label 1,2 => 部门1/部门2 */
export const formatCascaderLabel = (value: string, options: Option[]): string => {
    const arr = formatCascaderValue(value);
    if (arr) {
        const arrLabel = findCascaderLabel(arr, options);
        const strLabel = arrLabel.join('/');
        return strLabel;
    }
    return '';
}

export default function MyCascadePicker(props: IProps) {
    const { formControl, className = '', style = {} } = props;
    const {
        // value, setValue,
        readonly,
        outerClassName,
        options,
        layout,
        showError,
        outerStyle,
        labelStyle,
        selectorStyle,
        color,
    } = useFormItemInit(formControl, className, style);

    const [cascaderValue, setCascaderValue] = React.useState(formatCascaderValue(formControl.value));
    // console.log(`cascaderValue`, cascaderValue, formControl.value);

    const [visible, setVisible] = React.useState(false);

    /** 只读值 */
    const [readOnlyValue] = React.useState(findCascaderLabel(cascaderValue, options));


    /** 随机 className */
    const [randomClassName] = React.useState(`cascader-${Utils.getRandomChars(4)}`);
    /** 设置颜色 */
    const renderColor = () => {
        if (color) {
            return (
                <style>
                    {`
                        .${randomClassName} .ant-select-selector {
                            border-color: ${color} !important;
                        }
                    `}
                </style>
            )
        }
    }

    /** 清除 */
    const clean = () => {
        formControl.setValue(null, 'user');
    };

    /** 打开 */
    const open = () => {
        setVisible(true);
    };
    /** 关闭 */
    const close = () => {
        setVisible(false);
    };
    /** 确定 */
    const confirm = (v: any) => {
        console.log(v);
    }

    

    return (
        <>
            {renderColor()}
            <div component-name='form-item' className={outerClassName} style={outerStyle}>
                <div className={`field ${layout}`}>
                    <Components.forms.FormLabel formControl={formControl} style={labelStyle} />
                    <div className='control'>
                        <div className="value picker">
                            {/* 显示值 */}
                            <Readonly onSelectorClick={open} formControl={formControl} />
                            {
                                readonly === false && <>
                                    {/* 清除 */}
                                    <CloseCircleOutlined onClick={() => clean()} style={{ 'fontSize': '14px', 'marginLeft': '5px' }} />
                                    {/* 选择 */}
                                    <MenuOutlined onClick={() => open()} style={{ 'fontSize': '14px', 'marginLeft': '5px' }} />
                                    <CascadePicker
                                        // columns={columns}
                                        visible={visible}
                                        onClose={() => close()}
                                        // value={pickerValue}
                                        onConfirm={v => confirm(v)}
                                        options={options}
                                    />
                                </>
                            }
                        </div>
                    </div>
                </div>
            </div>
        </>
    )
}
